import pyaudio
import wave
from tqdm import tqdm
from pathlib import Path


def record_audio(wave_out_path, record_second):
    '''
    录音
    :param wave_out_path:文件输出路径
    :param record_second: 录制秒数
    :return: None
    '''
    FORMAT = pyaudio.paInt16  # 音频数据格式
    CHANNELS = 2  # 声道数
    RATE = 44100  # 采样率
    CHUNK = 1024  # 每次读多少个数据

    p = pyaudio.PyAudio()
    stream = p.open(format = FORMAT,
                    channels = CHANNELS,
                    rate = RATE,
                    input = True,
                    frames_per_buffer = CHUNK)

    wf = wave.open(wave_out_path, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))  # 其实就是2,表示两个字节
    wf.setframerate(RATE)

    print("* recording")

    ## RATE / CHUNK * record_second意思是：
    ## 采样率是RATE，每秒采集RATE个数据，所以每秒的音频需要读取RATE / CHUNK次
    for i in tqdm(range(0, int(RATE / CHUNK * record_second))):
        data = stream.read(CHUNK)
        wf.writeframes(data)
    print("* done recording")

    stream.stop_stream()
    stream.close()
    p.terminate()
    wf.close()

root_path=Path(__file__).parent.parent
path=root_path.joinpath("sounds/output.wav")
record_audio(str(path), record_second = 1)
